// pages/mine/petItem/index.js
import {formatDate} from '../../../../utils/util'
const app=getApp()

Page({

    /**
     * 页面的初始数据
     */
    data: {
        pet:'',
        petIndex:'',
        // petSick:'',
        // petVaccinate:'',
        petNotUpdate:true,
        petSickpetNotUpdate:true,
        petVaccinatepetNotUpdate:true,
        tempFormData:{
          pickerPetType: '',
          birthdayData: '',
          age:'',
        },
        petType:'',
        vaccinateType:'',
        // SickType:'',
        timeNow: formatDate(new Date()),
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        let petId = parseInt(options.petId)
        let petIndex = parseInt(options.petIndex)
        var that  = this
        that.setData({
          petIndex
        })
        that.InitializePetData(petId)
     
    },

    changePetImg(){
        var that = this 
        wx.chooseImage({
            count: 1,
            sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都
            sourceType: ['album', 'camera'], //从相册选择
            success: (res) => {
              console.log(res)
              let imgPath = res.tempFilePaths[0]
              // 上传图片
              wx.uploadFile({
                filePath: imgPath,
                name: 'file',
                url: app.globalData.prefixUrl + '/chong/wx/upload?userId=' + app.globalData.userId,
                header: {
                  "Content-Type": "multipart/form-data"
                },
                success(e) {
                  console.log("\n图片上传成功 "+e.data)
                  that.setData({
                    'pet.petPhoto':e.data
                  })
                  // that.data.pet.petPhoto = e.data
                  console.log("图片地址：" + that.data.pet.petPhoto)
                },
                fail(e){
                    console.log("\n图片上传失败: ", e)
                }
              })
              }
            }
          );
    },

   editPetInfo(){
      var that = this 
      let date = new Date();

      that.setData({
        petNotUpdate: false,
      })
      console.log("timeNow: ", that.data.timeNow);

      // petType
      wx.request({
        url: app.globalData.prefixUrl + '/chong/pet/type',
        method:"GET",
        success(e){
            console.log("获取所有宠物类型数据成功: " , e)
            that.setData({
              petType: e.data,
            })
        },
        fail(e){
          console.log("获取所有宠物类型数据失败: " + e)
        }
      })
      // vaccinateType
      wx.request({
        url: app.globalData.prefixUrl + '/chong/else/vaccineType/type',
        method:"GET",
        data:{
          petType: that.data.pet.type
        },
        success(e){
            console.log("获取该宠物所有疫苗数据成功: " , e)
            that.setData({
              vaccinateType: e.data
            })
        },
        fail(e){
          console.log("获取该宠物所有疫苗数据失败: " + e)
        }
      })
    },
    delPetInfo(){
      var that = this
      wx.showModal({
        title: '提示',
        content: '该宠物相关的所有信息都会被删除 !!!!!',
        cancelText: '取消',
        confirmText: '确认',
        success: res => {
          if (res.confirm) {
            that.delAllRelatedPetInfo()
            wx.navigateBack()
          }
        }
      })
    },
    cancelPetEdit(e){
      var that = this
      that.setData({
        petNotUpdate: true,
      })
      
    },
    changeDate(e){
      var that = this
      console.log("当前选中生日时间: ", e.detail.value)
      that.setData({ 
        'tempFormData.birthdayData':e.detail.value,
    });
      that.getAgeByBirthdar()
    },
    bindPickerChange: function (e) {
      var that = this
      console.log('picker发送选择改变，携带值为', e.detail.value)
      this.setData({
        pickerIndex: e.detail.value,
      })
      that.setData({
        'tempFormData.pickerPetType':that.data.petType[this.data.pickerIndex].type,
      })
    },

    // 更新表单提交
    petFormSubmit:function(e){
      var that = this
      var formData=e.detail.value;
      //获取上一个页面的对象
      var pages=getCurrentPages()
      var prevPage=pages[pages.length-2]
      let currPet = that.data.pet
      
      // 更新宠物数据
      wx.request({
        url: app.globalData.prefixUrl + "/chong/pet/pet/" + currPet.id,
        data:{
          id: currPet.id,
          nickname: formData.nickname,
          type: that.data.tempFormData.pickerPetType,
          petPhoto: that.data.pet.petPhoto,
          sex: formData.sex,
          age: formData.age,
          birthday: that.data.tempFormData.birthdayData,
          weitht: formData.weitht,
          height: formData.height,
          bodyLength: formData.bodyLength,
        },
        method:"PUT",
        header:{
          'Content-type': "application/x-www-form-urlencoded"
        },
        success(e){
         console.log("更新宠物数据成功: ", e)
         // 更新dailyInfo里的pet信息
         wx.request({
          url: app.globalData.prefixUrl + '/chong/record/daily/pet/' + currPet.id,
          data:{
              petNickname:formData.nickname,
              petPhoto:that.data.pet.petPhoto,
          },
          method:"PUT",
          header:{
            'Content-type': "application/x-www-form-urlencoded"
          },
          success(e){
              console.log("该宠物dailyInfo数据更新成功. ", e)
          }
        })
        },
        fail(e){
         console.log("更新宠物数据失败: ", e)
        }
      })

      let petIndex = that.data.petIndex
      let petInfos = prevPage.data.petInfos
      let prevPet = prevPage.data.petInfos[petIndex]
        prevPet.petPhoto = currPet.petPhoto,
        prevPet.nickname = formData.nickname,
        prevPet.type = that.data.tempFormData.pickerPetType,
        prevPet.sex = formData.sex,
        prevPet.age = formData.age,
      petInfos.splice(petIndex,1,prevPet)
      // console.log("上一个页面内容: ", prevPage)
      prevPage.setData({
        petInfos
      })
      //返回上一个页面
      wx.navigateBack()
    },

    InitializePetData(petId){
      var that = this
      // pet
      wx.request({
        url: app.globalData.prefixUrl + '/chong/pet/pet/' + petId,
        method:"GET",
        success(e){
            console.log("获取"+ petId +"宠物数据成功: " , e)
            that.setData({
                pet: e.data,
                'tempFormData.pickerPetType': e.data.type,
                'tempFormData.birthdayData':e.data.birthday,
            })
            that.getAgeByBirthdar()
        },
        fail(e){
          console.log("获取"+ petId +"宠物数据失败: " + e)
        }
      })
    },
    getAgeByBirthdar(){
      var that = this
      let date = that.data.tempFormData.birthdayData+"";
      let birthday = new Date(date.replace(/-/g, "\/"))
      let now = new Date
      let age = now.getFullYear()-birthday.getFullYear()-((now.getMonth()<birthday.getMonth()|| now.getMonth()==birthday.getMonth() && now.getDate()<birthday.getDate())?1:0);
      that.setData({
        'tempFormData.age': age
      })
      console.log("当前日期: ", now)
      console.log("宠物当前年龄: ", that.data.tempFormData.age)
    },
    delAllRelatedPetInfo(){
      var that = this
      // del petInfo
      wx.request({
        url: app.globalData.prefixUrl+ '/chong/pet/pet/' + that.data.pet.id,
        method:"DELETE",
        success(e){
          console.log("宠物基本"+that.data.pet.id+"删除成功: ", e)
        },
        fail(e){
          console.log("宠物基本"+that.data.pet.id+"删除失败: ", e)
        }
      })
      // del petSick
      wx.request({
        url: app.globalData.prefixUrl+ '/chong/pet/sick/pet/' + that.data.pet.id,
        method:"DELETE",
        success(e){
          console.log("宠物基本信息"+that.data.pet.id+"删除成功: ", e)
        },
        fail(e){
          console.log("宠物基本信息"+that.data.pet.id+"删除失败: ", e)
        }
      })
      // del petVaccinate
      wx.request({
        url: app.globalData.prefixUrl+ '/chong/pet/vaccinate/pet/' + that.data.pet.id,
        method:"DELETE",
        success(e){
          console.log("宠物"+that.data.pet.id+"删除成功: ", e)
        },
        fail(e){
          console.log("宠物"+that.data.pet.id+"删除失败: ", e)
        }
      })
      // del pet daily
        wx.request({
          url: app.globalData.prefixUrl+ '/chong/record/daily/pet/' + that.data.pet.id,
          method:"DELETE",
          success(e){
            console.log("宠物每日记录信息"+that.data.pet.id+"删除成功: ", e)
          },
          fail(e){
            console.log("宠物每日记录信息"+that.data.pet.id+"删除失败: ", e)
          }
        })
    },
})